package com.wrupple.muba.desktop.client.bootstrap.state.impl;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.inject.Inject;
import com.wrupple.muba.common.shared.StateTransition;
import com.wrupple.muba.desktop.client.bootstrap.state.LoadDesktopDescriptor;
import com.wrupple.muba.desktop.client.events.DesktopModelReceivedEvent;
import com.wrupple.muba.desktop.domain.DesktopDescriptor;
import com.wrupple.muba.desktop.domain.DesktopLoadingStateHolder;
import com.wrupple.muba.desktop.shared.services.GetAppDescriptorService;
import com.wrupple.muba.desktop.shared.services.GetAppDescriptorServiceAsync;

public class LoadDesktopDescriptorImpl implements LoadDesktopDescriptor {
	
	 class DesktopModelCallback implements AsyncCallback<DesktopDescriptor>{
		StateTransition<DesktopLoadingStateHolder> onDone;
		private EventBus eventBus;
		
		public DesktopModelCallback(StateTransition<DesktopLoadingStateHolder> onDone,EventBus eventBus) {
			super();
			this.onDone = onDone;
			this.eventBus=eventBus;
		}

		@Override
		public void onFailure(Throwable caught) {
			// TODO Auto-generated method stub
			Window.alert("I am not feeling well. Sorry.");
		}

		@Override
		public void onSuccess(DesktopDescriptor result) {
			DesktopLoadingStateHolder grandNew = new DesktopLoadingStateHolder();
			grandNew.setDesktopDescriptor(result);
			eventBus.fireEvent(new DesktopModelReceivedEvent(result));
			onDone.setResultAndFinish(grandNew);
		}
		
	}
	
	
	@Inject
	public LoadDesktopDescriptorImpl() {
		super();
	}



	@Override
	public void start(DesktopLoadingStateHolder parameter, StateTransition<DesktopLoadingStateHolder> onDone,EventBus eventBus ) {
		GetAppDescriptorServiceAsync descriptorService = GWT.create(GetAppDescriptorService.class);
		descriptorService.getDesktop(new DesktopModelCallback(onDone, eventBus));
	}


}
